#!/usr/bin/env python
#


import wsgiref.handlers

from google.appengine.ext import webapp
from google.appengine.api import memcache
from Parser import *
from FRCHelper import *

DESC = False
ASC = True

events = ("az","or","nh","la","in","ma","oh","md","co","ct","da","roc","fl","kc","on","hi","is","nv","tx","ca","wa","il","mn","mn2","nj","ny","nc","ok","sc","ga","pa","pit","sac","sdc","li","sj","mo","ut","va","dc","wat","wi","wor","wc","dt1","dt","gg","gt","oc","mi")

class RequestHandler(webapp.RequestHandler):

	def write(self,x):
		self.response.out.write(x)
	
	def get(self):
#		URLS = map(lambda code: "http://www.frclinks.com/e/m/%s/2009"%(code),events)
#		URL = "https://my.usfirst.org/myarea/index.lasso?page=teamlist&event_type=FRC&sort_teams=number&year=2009&event=gg"
		if self.request.get('event') == '':
			return
		matches = memcache.get("%s:%s"%(self.request.get('event'),'qm'))
		if matches is None:
			DT1 = HorizontalParser(FRCLinks_URL_Loader("http://www.frclinks.com/e/m/%s/2009"%(self.request.get('event'))))
			matches = QualificationMatches(DT1)
			memcache.add("%s:%s"%(self.request.get('event'),'qm'),matches, 3000)
#		self.write(matches)
		filters = parseFilters(self.request.get_all('filters'))
		filtered = filter(filterByAny(filters),matches)
		if len(filtered) == 0:
			return
		self.write("<table width='100%'>")
		self.write("<tr>")
		map(lambda col: self.write("<td>%s</td>"%(col)),filtered[1].keys())
		self.write("</tr>")
		for row in filtered:
			self.write("<tr>")
			for cell in row.values():
				self.write("<td>%s</td>"%(cell))
			self.write("</tr>")
		
#		Attendance  = map(lambda Event: (Event,TeamList(HorizontalParser(FRCLinks_URL_Loader("http://www.frclinks.com/e/%s"%(Event))))), events[0])
#		self.write(json.dumps(Attendance))
#		self.write(self.request.get_all('filter'))
		
def main():
  application = webapp.WSGIApplication([('.*', RequestHandler)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)


if __name__ == '__main__':
  main()
